package com.lcb.manager.web;

import com.alibaba.fastjson.JSON;
import com.lcb.manager.entity.User;
import com.lcb.manager.repository.UserRepository;
import com.lcb.manager.vo.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value = "/")
    public String index() {
        return "login";
    }

    @ResponseBody
    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String pwd, @RequestParam Integer role, HttpSession session) {
        Json result = new Json();
        List<User> userList = userRepository.findUserByName(username);
        if (userList.size() == 0) {
            result.code = 1;
            result.msg = "用户不存在！";
            return JSON.toJSONString(result);
        }
        User user = userList.get(0);
        result.data= user.getRole();
        if (!pwd.equals(user.getPwd())) {
            result.code = 1;
            result.msg = "用户密码不正确！";
            return JSON.toJSONString(result);
        } else if (!user.getRole().equals(role)) {
            result.code = 1;
            result.msg = "用户角色不正确！";
            return JSON.toJSONString(result);
        } else {
            session.setAttribute("is_login", true);
            session.setAttribute("user", user);
            result.code = 0;
            return JSON.toJSONString(result);
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }
}
